import 'dart:convert';
import 'dart:io';

import 'package:ac/api/ac_urls.dart';
import 'package:ac/common/ac_pv_manager.dart';
import 'package:ac/common/ac_upload_util.dart';
import 'package:ac/data/ac_user_manager.dart';
import 'package:ac/model/ac_login_model.dart';
import 'package:ac/model/ac_strategy_model.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

import 'ac_me_state.dart';

class AcMeLogic extends GetxController {
  final AcMeState state = AcMeState();
  final userInfo = Rxn<Userinfo>();
  late AcStrategyModel strategyModel;
  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    userInfo.value = AcUserManager.userInfoModel?.userInfo;
    // 获取客服ID
    _getCustomerServiceId();
  }

  Future<void> updateAvatar() async {
    LogPvManger.stat(page: LogPages.editAvatarPage);
    PermissionStatus status = await Permission.camera.request();
    if (!status.isGranted) {
      EasyLoading.showToast("You have not authorised this permission.");
      return;
    }
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.camera);
    if (image == null) {
      return;
    }
    EasyLoading.show(
        status: 'uploading...',
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false);
    var avatarPath = await AcUploadUtil.uploadFile(File(image.path));
    var res = await AcUrls.updateAvatar.post(
      data: {"avatarPath": avatarPath},
      showLoading: false,
    );
    if (res?["code"] == 0) {
      var avatarUrl = res?["data"]["mediaUrl"];
      var thumbUrl = res?["data"]["thumbUrl"];
      var middleThumbUrl = res?["data"]["middleThumbUrl"];
      userInfo.value!.avatarUrl = avatarUrl;
      userInfo.value!.avatarThumbUrl = thumbUrl;
      userInfo.value!.avatarMiddleThumbUrl = middleThumbUrl;
      AcUserManager.updateLoginUserInfo(userInfo.value!);
      userInfo.refresh();
    } else {
    }
    EasyLoading.dismiss();
  }

  Future<void> _getCustomerServiceId() async {
    var result = await AcUrls.getStrategy
        .get(showLoading: false, showErrorMessage: false);
    strategyModel = AcStrategyModel.fromJson(result?["data"]);
  }
}
